package com.um.jdy.common.device.service.impl;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.um.jdy.common.device.enums.DeviceEnum;
import com.um.jdy.rpc.api.RpcEVDeviceService;
import com.um.jdy.rpc.ev.confirmation.SetPriceModelConfirmation;
import com.um.jdy.rpc.factory.ServiceFactory;
import com.um.springboot.starter.utils.StringUtil;
import com.um.springcloud.dubbo.cluster.DeviceKey;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.TaskScheduler;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import com.um.springboot.starter.orm.service.BaseEntityServiceImpl;
import com.um.jdy.common.device.service.PileService;
import com.um.jdy.common.device.dao.PileDao;
import com.um.jdy.common.device.entity.po.Pile;

import java.util.Random;

/**
 * 服务实现类：充电桩表
 */
@Service
@Slf4j
public class PileServiceImpl extends BaseEntityServiceImpl<PileDao,Pile>  implements PileService{

    @Autowired
    ServiceFactory serviceFactory;

    @Autowired
    TaskScheduler taskScheduler;

    @Override
    public void remoteUpdatePrice(Pile pile) {

        Random random = new Random();
        int ranNum = random.nextInt(91)+10;//[10,100]
        //随机数，延迟更新价格
        taskScheduler.schedule(() -> scheduleUpdatePrice(pile),
                DateUtil.date().offset(DateField.SECOND, ranNum));
    }

    private void scheduleUpdatePrice(Pile pile){
        if (!StringUtil.equals(pile.getDeviceStatus(), DeviceEnum.DeviceStatus.Online.name())) {
            return;
        }

        try {
            serviceFactory.getRpcEVDeviceService(pile.getProtocol()).setPriceModel(new DeviceKey(pile.getImei()));
            log.error("更新价格成功：{}",pile.getCode());
        }catch (Exception ex){
            log.error("更新价格失败：{}-{}",pile.getCode(),ex.getMessage());
        }
    }
}
